package cc.atliberty.oa.controller;

import cc.atliberty.oa.pojo.Dept;
import cc.atliberty.oa.service.DeptService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@WebServlet("/dept/add")
public class AddDeptServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("html/text;charset=utf-8");
        // 获取前端发送的数据
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        // 封装到对象中
        Dept dept = new Dept(deptno,dname,loc);
        // 添加部门信息到数据库
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        DeptService deptService = context.getBean("deptService", DeptService.class);
        int i = deptService.saveDept(dept);
        if (i == 1){
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
